<template>
  <!--锚点-->
  <div v-if="showAnchor" v-for="(anchor,index) of props.option.anchors" :key="index" class="link-anchor"
       :style='{"top":((anchor.point.y*zoom)+"px"),"left":((anchor.point.x*zoom)+"px"),"display":(anchor.visiable?"":"none")}'
       @click="handleAnchorClick" @dragstart="handleAnchorDragstart" @mousedown="handleMouseDown($event,anchor)"
       @dblclick="handleDoubleClick($event,anchor)">
  </div>
</template>
<script setup lang="ts">
import {inject, onMounted, Ref, ref, watch} from "vue";
import {ComponentAnchor, ComponentOption} from "./ComponentOption.ts";

const panelEvents: any = inject("panelEvents")
const props = defineProps({
  option: {type: ComponentOption, required: true},
  showAnchor: {type: Boolean, required: false},
  zoom: {type: Number, required: true}
});
const showAnchor = ref(false)
watch([() => props.option.selected, () => props.showAnchor], ([nse, nsh], [ose, osh]) => {
  refreshIfShow(nse, nsh)
})

function refreshIfShow(nse: boolean, nsh: boolean) {
  if (nse) {
    showAnchor.value = true
  } else {
    showAnchor.value = nsh
  }
}

refreshIfShow(props.option.selected, props.showAnchor)
watch([() => props.option], () => {
  props.option.figure()
}, {deep: true})
props.option.figure()

const x: Ref<number> = ref(0)
const y: Ref<number> = ref(0)
const w: Ref<number> = ref(60)
const h: Ref<number> = ref(60)

function setSize(_w: number, _h: number) {
  w.value = _w;
  h.value = _h;
}

function setPosition(_x: number, _y: number) {
  x.value = _x;
  y.value = _y;
}

function setGeo() {
  x.value = props.option.x
  y.value = props.option.y
  w.value = props.option.w
  h.value = props.option.h
}

x.value = props.option.x
y.value = props.option.y
w.value = props.option.w
h.value = props.option.h
defineExpose({setSize, setPosition, setGeo})
onMounted(() => {

})

function handleAnchorClick(event: MouseEvent) {

  event.stopPropagation();
}

function handleAnchorDragstart(event: DragEvent) {
  event.preventDefault()
  event.stopPropagation();
}

function handleMouseDown(event: MouseEvent, anchor: ComponentAnchor) {
  event.preventDefault();
  event.stopPropagation();
  if (event.button !== 0) {
    return
  }
  panelEvents.drawLinkStart(props.option, anchor, event);
}

function handleDoubleClick(event: MouseEvent, anchor: ComponentAnchor) {
  //双击删除锚点
  event.preventDefault();
  event.stopPropagation();
  let index = props.option?.anchors.indexOf(anchor);
  props.option?.anchors.splice(index, 1);
}
</script>
<style lang="scss" scoped>
.link-anchor {
  position: absolute;
  border: 2px solid rgba(255, 0, 0, 0.6);
  box-sizing: border-box;
  border-radius: 50%;
  width: 10px;
  height: 10px;
  background-color: rgba(255, 255, 255, 1);
  cursor: pointer;
  transform: translateX(-50%) translateY(-50%);
  z-index: 2;
}
</style>
